<script src="../../../../../../user.js"></script>
<template>
  <el-dialog
    v-el-drag-dialog
    title="回执确认"
    :visible.sync="visible"
    width="1024px"
    @closed="reset"
  >
    <el-form ref="dataForm" :inline="true" :rules="rules" :model="temp">
      <el-descriptions size="medium" :column="2" style="margin-bottom: 20px;">
        <el-descriptions-item label="客户编号">{{ order.csmCode }}</el-descriptions-item>
        <el-descriptions-item label="客户名称">{{ order.csmName }}</el-descriptions-item>
        <el-descriptions-item label="客户地址">{{ order.csmAddress }}</el-descriptions-item>
      </el-descriptions>
      <el-form-item label="责任机构:" prop="orgSNNo">
        <el-tree-select
          v-model="temp.orgSNNo"
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'default-expand-all': true,
            'expand-on-click-node': false,
            'highlight-current': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item label="处理人:" prop="userId">
        <el-select v-model="temp.userId" :loading="$loadingPlugin.getOwnersList" style="width: 100%;" placeholder="请选择">
          <el-option
            v-for="item in ownersList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="支付方式:">
        <el-select v-model="temp.paymentMethod" placeholder="请选择" @change="paymentChange">
          <el-option
            v-for="item in paymentMethodMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="确认人:" prop="reCheckUserName">
        <el-input v-model="temp.reCheckUserName" style="width: 80px;" />
      </el-form-item>
    </el-form>
    <lb-table
      ref="lbTable"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      show-summary
      @fetch="fetchData"
    />
    <el-descriptions size="medium" :column="2" style="margin-top: 20px;" :label-style="{'color': '#F24024'}" :content-style="{'color': '#F24024'}">
      <el-descriptions-item label="总应收">{{ order.treceivables || 0 }}</el-descriptions-item>
      <el-descriptions-item label="总实收">{{ totalReflections }}</el-descriptions-item>
    </el-descriptions>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        取消
      </el-button>
      <el-button :loading="$loadingPlugin.success" type="primary" @click="success">
        确认回执
      </el-button>
    </div>
    <prepaid-card ref="prepaidCard" />
  </el-dialog>
</template>

<script>
  import {
    querySignOrderOrderBillData,
    queryCsmCardCodeByOrderCode,
    submitReceiptConfirm,
    queryOwnerList
  } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import PrepaidCard from './PrepaidCard'

  export default {
    name: 'receipt-confirm',
    props: {
      paymentMethodMap: {
        type: Array,
        required: true
      }
    },
    components: {
      PrepaidCard
    },
    data() {
      return {
        visible: false,
        treeData: [],
        ownersList: [],
        showCsmCard: false, // 是否显示预付卡
        check_csmCard_ok_info: {
          check_csmCard_ok_status: false, // 是否校验通过预付卡密码或验证码 true表示校验通过 false表示校验失败
          check_csmCard_ok_msg: ''
        },
        csmName: '',
        csmPhone: '',
        row: {},
        temp: {
          orgSNNo: '',
          userId: '',
          paymentMethod: 1,
          reCheckUserName: '007'
        },
        rules: {
          reCheckUserName: [{ required: true, message: '请输入确认人', trigger: 'change' }]
        },
        detail: {},
        order: {
          treceivables: 0
        },
        tableData: {
          column: [
            {
              prop: 'goodsName',
              label: '商品名称'
            },
            {
              prop: 'specCode',
              label: '规格型号',
              render: (h, scope) => {
                return (
                  <div>
                    {
                      scope.row._edit && scope.column.pricingMode === 2
                        ? <el-input value={ scope.row[scope.column.property] } onInput={ (val) => { scope.row[scope.column.property] = val } }></el-input>
                        : <span>{ scope.row[scope.column.property] }</span>
                    }
                  </div>
                )
              }
            },
            {
              prop: 'gcount',
              align: 'right',
              label: '数量'
            },
            {
              prop: 'gasWeight',
              align: 'right',
              width: 100,
              label: '送出重量',
              render: (h, scope) => {
                return (
                  <div>
                    {
                      scope.row._edit && scope.column.pricingMode === 2
                        ? <el-input value={ scope.row[scope.column.property] } onInput={ (val) => { scope.row[scope.column.property] = val.replace(/[^\d.]/g, '').replace(/^0\d+|^\./g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(.*\..{2}).*$/, '$1') } }></el-input>
                        : <span>{ scope.row[scope.column.property] }</span>
                    }
                  </div>
                )
              }
            },
            {
              prop: 'fee3',
              align: 'right',
              label: '回收重量'
            },
            {
              prop: 'netWeight',
              align: 'right',
              label: '净重'
            },
            {
              prop: 'gprince',
              align: 'right',
              label: '单价'
            },
            {
              prop: 'gprefPrice',
              align: 'right',
              label: '优惠价格'
            },
            {
              prop: 'fee1',
              align: 'right',
              label: '配送费'
            },
            {
              prop: 'fee2',
              align: 'right',
              label: '上楼费'
            },
            {
              prop: 'tip',
              align: 'right',
              label: '服务费'
            },
            {
              prop: 'treceivable',
              align: 'right',
              label: '总应收',
              render: (h, { row }) => <span>{ row.treceivable ? Number(row.treceivable).toFixed(2) : '' }</span>
            },
            {
              prop: 'accReceivable',
              align: 'right',
              width: 100,
              label: '实收金额',
              render: (h, scope) => {
                return (
                  <div>
                    {
                      scope.row._edit
                        ? <el-input value={ scope.row[scope.column.property] } onInput={ (val) => { scope.row[scope.column.property] = val.replace(/[^\d.]/g, '').replace(/^0\d+|^\./g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(.*\..{2}).*$/, '$1') } }></el-input>
                        : <span>{ Number(scope.row[scope.column.property]).toFixed(2) }</span>
                    }
                  </div>
                )
              }
            },
            {
              label: '操作',
              width: 140,
              alignt: 'center',
              fixed: 'right',
              render: (h, scope) => {
                return (
                  <div>
                    {
                      scope.row._edit
                        ? <div>
                          <el-button type='primary' onClick={ () => { this.handleSave(scope) } }>保存</el-button>
                          <el-button onClick={ () => { this.handleCancle(scope) } }>取消</el-button>
                        </div>
                        : <el-button type='primary'
                                     onClick={ () => { this.handleEdit(scope) } }>编辑</el-button>
                    }
                  </div>
                )
              }
            }
          ],
          data: [],
          defaultData: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList', 'corpSettingData'
      ]),
      // 总实收
      totalReflections: function() {
        if (this.tableData.data.length === 0) return 0
        return this.tableData.data.reduce((prev, cur) => prev + Number(cur.accReceivable), 0)
      }
    },
    methods: {
      async open(temp) {
        await Promise.all([this.getTreeData(), this.getOwnersList(temp.orgId), this.getShowCsmCardValue()])
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
          if (temp) {
            this.row = temp
            this.temp.orgSNNo = temp.orgSNNo
            this.temp.userId = temp.ownerId
            this.detail = temp
            this.csmName = temp.csmName
            this.csmPhone = temp.csmPhone
          }
        })
      },
      // 查询是否显示预付卡
      async getShowCsmCardValue() {
        this.showCsmCard = Math.random() >= 0.5
        if (!this.showCsmCard) {
          const index = this.paymentMethodMap.findIndex(item => item.value === 256)
          this.paymentMethodMap.splice(index, 1) // 删除预付卡
        }
      },
      // 支付方式改变
      async paymentChange(value) {
        // 支付方式修改,则重置预付卡验证状态
        this.$set(this.check_csmCard_ok_info, 'check_csmCard_ok_status', false)
        this.$set(this.check_csmCard_ok_info, 'check_csmCard_ok_msg', '')
        // 预支付并且之前订单不是预付卡支付
        if (value === 256 && this.order.paymentMethod !== 256) {
          // 结束编辑
          if (this.tableData.data.some(item => item._edit)) {
            this.$message.warning('请结束编辑！')
            return
          }
          // 校验预支付账号是否存在,预支付金额是否足够支付
          this.selectCsmCardCodeByOrderCode()
        }
      },
      // 根据批发订单查询客户预付卡
      async selectCsmCardCodeByOrderCode() {
        const res = await queryCsmCardCodeByOrderCode({
          orderCode: this.detail.orderCode,
          billType: 1,
          payMoney: this.totalReflections
        })
        // 客户可用预付卡卡号
        // const cardCode = res.data.cardCode
        const checkWay = res.data.accCsmCardConfigInfo.checkWay
        // 规则配置不是无校验
        if (checkWay !== 1) {
          // 打开预付卡弹框
          this.$refs.prepaidCard.open(res.data)
        } else {
          this.$set(this.check_csmCard_ok_info, 'check_csmCard_ok_status', true)
          this.$set(this.check_csmCard_ok_info, 'check_csmCard_ok_msg', '')
        }
      },
      // 获取责任机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 获取详情数据
      async fetchData() {
        const res = await querySignOrderOrderBillData({ orderCode: this.row.orderCode })
        this.order = res.data
        this.order.treceivables = res.data.treceivables
        this.tableData.data = res.data.detailList
        this.tableData.defaultData = JSON.parse(JSON.stringify(this.tableData.data))
        if (this.order.payStatus === 1) {
          let hasPricingMode2 = false // 是否有按单位计价的商品
          for (let i = 0; i < res.data.detailList.length; i++) {
            if (res.data.detailList[i].pricingMode === 2) {
              hasPricingMode2 = true
            }
            const detail = res.data.detailList[i]
            // 净气未完成的，实收为空;普通商品实收默认应收
            if (this.order.orderStatus !== 10 && detail.pricingMode === 2) {
              detail.accReceivable = null
            } else {
              detail.accReceivable = detail.treceivable
            }
            detail.gasWeight = (detail.fee3 || 0) + (detail.netWeight || 0)
            if (detail.gasWeight === 0) {
              detail.gasWeight = null
            }
          }
          if (hasPricingMode2 === false) {
            this.order.taccReceivable = this.order.treceivables
          }
        }
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.temp.orgId = value.orgId
        this.getOwnersList(value.orgId)
        this.$set(this.temp, 'userId', '')
      },
      // 查询处理人列表
      async getOwnersList(orgId) {
        const b = this.corpSettingData.sp1 >> 2 & 0x01
        const res = await queryOwnerList({
          orgId,
          corpparm1: b
        })
        this.ownersList = res.data
      },
      async success() {
        if (this.tableData.data.some(item => item._edit)) {
          this.$message.warning('请结束编辑！')
          return
        }
        this.$refs.dataForm.validate(valid => {
          if (!valid) return
          const rows = this.tableData.data
          for (let i = 0; i < this.paymentMethodMap.length; i++) {
            // 支付方式存在预支付
            if (this.order.payStatus !== 3 && this.paymentMethodMap[i].value === 256) {
              if (!this.check_csmCard_ok_info.check_csmCard_ok_status) {
                if (this.check_csmCard_ok_info.check_csmCard_ok_msg === '') {
                  this.$message.warning('使用预支付需要校验密码或验证码')
                  return
                } else {
                  this.$message.warning(`${this.check_csmCard_ok_info.check_csmCard_ok_msg}`)
                  return
                }
              }
            }
          }
          const matchOrg = this.orgList.find(item => item.orgSNNo === this.temp.orgSNNo)
          const matchUser = this.ownersList.find(item => item.userId === this.temp.userId)
          const params = {
            paymentMethod: this.temp.paymentMethod,
            tReceivables: this.order.tReceivables,
            taccReceivable: this.totalReflections,
            accReceivable: this.totalReflections,
            reCheckUserName: this.temp.reCheckUserName,
            orgId: matchOrg.orgId,
            orgName: matchOrg.orgName,
            orgSNNo: matchOrg.orgSNNo,
            ownerId: matchUser.userId,
            ownerName: matchUser.userName,
            ownerCode: matchUser.userCode,
            orderCode: this.order.orderCode,
            relBackGas: this.order.relBackGas,
            generalGas: this.order.generalGas,
            detailList: rows
          }
          if (this.order.corpCode === '37049' && this.order.relBackGas > 0 && params.relBackGas === 0) {
            params.relBackGas = this.order.relBackGas
          }
          let msg = '实收金额:' + params.taccReceivable + '，确认提交吗？'
          if (this.order.orderStatus < 10) {
            // msg = "<span style='color:red;font-weight:bold'>此订单未完成</span><br/>" + msg
            msg = "此订单未完成!!!" + msg
          }
          this.$confirm(`${msg}`, '提示', {
            type: 'warning'
          }).then(() => {
            const loading = this.$message({
              message: '正在提交',
              duration: 0,
              iconClass: 'el-icon-loading'
            })
            submitReceiptConfirm(params).then(() => {
              this.resolve()
              this.visible = false
              this.$notify({
                title: '提示',
                message: '操作成功',
                type: 'success',
                duration: 2000
              })
            }).finally(() => {
              loading.close()
            })
          })
        })
      },
      handleEdit(scope) {
        this.$set(scope.row, '_edit', true)
      },
      handleSave(scope) {
        if (scope.column.pricingMode === 2) {
          if (!scope.column.gasWeight || scope.column.gasWeight * 1 <= 0) {
            this.$message.warning('请填写送出重量')
            return
          }
          if (scope.column.accReceivable === '' || scope.column.accReceivable == null) {
            this.$message.warning('请填写实收金额')
            return
          }
          if (!scope.column.specCode) {
            this.$message.warning('请选择规格')
            return
          }
        }
        this.$set(scope.row, '_edit', false)
        this.$set(this.tableData.defaultData, scope.$index, JSON.parse(JSON.stringify(scope.row)))
      },
      handleCancle(scope) {
        this.$set(this.tableData.data, scope.$index, JSON.parse(JSON.stringify(this.tableData.defaultData[scope.$index])))
      },
      reset() {
        this.paymentMethodMap = [{ 'value': 1, 'desc': '现金', 'key': 'MONEY' }, { 'value': 2, 'desc': '微信支付', 'key': 'WECHAT' }, { 'value': 4, 'desc': '气票', 'key': 'QP' }, { 'value': 16, 'desc': '月结', 'key': 'YJ' }, { 'value': 32, 'desc': '微信抵扣券', 'key': 'WX_DK' }, { 'value': 64, 'desc': '威富通', 'key': 'SWIFTPASS' }, { 'value': 128, 'desc': '支付宝', 'key': 'ALIPAY' }, { 'value': 256, 'desc': '预付卡', 'key': 'CSMCARD' }, { 'value': 512, 'desc': '国志钱包', 'key': 'ICBCEPAY' }, { 'value': 1024, 'desc': '工行支付', 'key': 'ICBCPAY' }]
        this.temp = {
          orgSNNo: '',
          userId: '',
          paymentMethod: 1,
          reCheckUserName: '007'
        }
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>

</style>
